//
//  FSSGViewController.m
//  Estate
//
//  Created by heyong on 16/5/27.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "FSSGViewController.h"
#import "SegmentViewController.h"

@interface FSSGViewController ()
{
    DBHelper *_helper;
    FMDatabase *_db;
    SegmentViewController *vc;
}
//设置按钮标题
@property (retain, nonatomic)NSArray *titArr;

@end

@implementation FSSGViewController

- (Site_02 *)site{
    if(_site==nil){
        _site=[[Site_02 alloc]init];
    }
    return _site;
}

#pragma mark-懒加载
- (NSArray *)titArr{
    if(_titArr==nil){
        _titArr=[NSArray arrayWithObjects:@"基本资料",@"人",@"机械",@"物料",@"法/环",nil];
    }
    return _titArr;
}

- (void)viewWillAppear:(BOOL)animated{    
    //根据flag 选择性刷新页面
    if(self.isSubStr!=nil){
        [self createsliderBtn];
    }
}

//解决查看后 再次添加 无法显示保存按钮的bug
- (void)setFlag:(NSString *)flag{
    _flag=flag;
    if([self.flag isEqualToString:@"addty"]){
        self.edit=YES;
        self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }else if ([self.flag isEqualToString:@"look"]){
        self.edit=NO;
    }else if ([self.flag isEqualToString:@"upRecord"]){
        //判断是否超过旁站结束时间 或者 日记提取了此条记录
        //self.edit=[LSUtility isSameDay:self.site.createTime];
        self.edit=[LSUtility siteEditForendTimeAndSiteRecordId:self.site.recordId beginTine:self.site.createTime endTime:self.site.endTime];
        if(self.edit){
            //添加右上方提交按钮
            self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
        }else{
            self.navigationItem.rightBarButtonItem=nil;
        }
    }
}

-(void)setSideId:(NSString *)sideId{
    _sideId=sideId;
    WEAKSELF
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *helper=[DBHelper help];
    NSDictionary *supData=[[helper DataBase:db selectKeyTypes:@{@"RECORD_NUMBER":@"text",@"RECORD_INFO":@"text",@"CREATE_TIME":@"text",@"ADDRESS_ID":@"text",@"ADDRES_INFO":@"text",@"RECORD_FILE_PATH":@"text"} fromTable:WORK_RECORD whereCondition:@{@"ID":sideId}]lastObject];
    
    NSString *dataJson=supData[@"RECORD_INFO"];
    NSDictionary *siteDic=[LSUtility dictionaryWithJsonString:dataJson];
    
    //得到附件数组
    NSString *fileJson=DEFISNUL(supData[@"RECORD_FILE_PATH"]);
    weakSelf.site.fileArray=[LSUtility dictionaryWithJsonString:fileJson];
    
    //位置
    weakSelf.site.locationInfo=DEFISNUL(siteDic[@"locationInfo"]);
    weakSelf.site.locationId=DEFISNUL(siteDic[@"ADDRESS_ID"]);
    weakSelf.site.location=DEFISNUL(siteDic[@"ADDRES_INFO"]);

    weakSelf.site.recordId=_sideId;
    weakSelf.site.createTime=supData[@"CREATE_TIME"];
    //人
    NSDictionary *RDic=siteDic[@"人"];
    weakSelf.site.gongbanNum=RDic[@"工班人数"];
    weakSelf.site.zaigangNum=RDic[@"施工单位质检在岗人员"];
    weakSelf.site.guanliNum=RDic[@"管理人数"];
    weakSelf.site.isR=RDic[@"是否满足施工组织需要"];
    weakSelf.site.teshuNum=RDic[@"施工人数"];
    
    //法环
    NSDictionary *FHDic=siteDic[@"法环"];
    weakSelf.site.isfh_1=FHDic[fs_msg_1];
    weakSelf.site.isfh_2=FHDic[fs_msg_2];
    weakSelf.site.isfh_3=FHDic[fs_msg_3];
    weakSelf.site.isfh_4=FHDic[fs_msg_4];
    weakSelf.site.isfh_5=FHDic[fs_msg_5];
    weakSelf.site.isfh_6=FHDic[fs_msg_6];
    weakSelf.site.isfh_7=FHDic[fs_msg_7];
    weakSelf.site.isfh_8=FHDic[fs_msg_8];
    weakSelf.site.isfh_9=FHDic[fs_msg_9];
    weakSelf.site.fh_text=FHDic[fs_msg_10];
    
    //机械
    NSDictionary *JXDic=siteDic[@"机械"];
    weakSelf.site.jixie_1=JXDic[@"设备1名称"];
    weakSelf.site.jixie_2=JXDic[@"设备2名称"];
    weakSelf.site.jixie1_num=JXDic[@"设备1台数"];
    weakSelf.site.jixie2_num=JXDic[@"设备2台数"];
    weakSelf.site.qiyou_num=JXDic[@"汽油喷灯"];
    weakSelf.site.isJ=JXDic[@"是否满足施工组织需要"];
    
    weakSelf.site.isJ_1=JXDic[@"上述各项机械设备运转是否正常"];
    
    //物料
    NSDictionary *WLDic=siteDic[@"物料"];
    weakSelf.site.wl_name=WLDic[@"防水材料的名称"];
    weakSelf.site.wl_pingpai=WLDic[@"品牌名称"];
    weakSelf.site.wl_xinghao=WLDic[@"型号"];
    weakSelf.site.wl_houdu=WLDic[@"防水卷材厚度"];
    weakSelf.site.isWl=WLDic[@"防水卷材是否经进场复试合格"];
    
    //基本信息
    NSDictionary *XXDic=siteDic[@"基本信息"];
    weakSelf.site.beginTime=XXDic[@"开始时间"];
    weakSelf.site.endTime=XXDic[@"结束时间"];
    weakSelf.site.weather=XXDic[@"天气"];
    weakSelf.site.danwei=XXDic[@"施工单位"];
    weakSelf.site.jlName=XXDic[@"旁站监理人"];
    weakSelf.site.diqu=XXDic[@"地区"];
    weakSelf.site.number=supData[@"RECORD_NUMBER"];
    //工序
    NSDictionary *XXDic_1=XXDic[@"工序"];
    weakSelf.site.otherAddress=XXDic_1[@"关键工序"];
    weakSelf.site.duan=XXDic_1[@"段"];
    weakSelf.site.ceng=XXDic_1[@"层"];
    weakSelf.site.lou=XXDic_1[@"楼"];
}

- (void)viewDidDisappear:(BOOL)animated{
    
    //清除flag：确保进入二级页面后 返回数据不会清空
    self.isSubStr=nil;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"旁站-防水施工-记录";
    self.view.backgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];

    _helper=[DBHelper help];
    _db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
}

#pragma  mark -返回保存按钮
- (void)clickSave{
    //施工单位必填
    if([self.fszlCtr.dataDic[@"施工单位"] isEqual:@""]){
        [LSUtility showToastWithMessage:@"请选择施工单位" inView:self.view Andtime:1.];
    }
    else if(self.fszlCtr.locationDic[@"locationInfo"]==nil)
    {
        [LSUtility showToastWithMessage:@"位置信息不能为空" inView:self.view Andtime:1.];
    }else if(!self.fszlCtr.dataDic[@"结束时间"]){
        [self.fszlCtr.dataDic setObject:[LSUtility nowTime] forKey:@"结束时间"];
    }
    else{
        if([self.flag isEqualToString:@"addty"]){
            [self addDataBase];
        }else if ([self.flag isEqualToString:@"upRecord"]){
            [self upDataBase];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}


#pragma mark - 新增数据
- (void)addDataBase{
    WEAKSELF
    
    NSString *recordId=[NSUUID UUID].UUIDString;
    
    NSMutableArray *fileArr= [self insertAttachment:recordId];
    
    NSString *recordInFoPath=[LSUtility dictionaryToJson_2:fileArr];
    
    /*
     *  工作记录表新增数据
     **/
    //数据结构法，存入数据库
    NSDictionary *dataDic=@{@"人":weakSelf.fsrhCtr.dataDic,@"法环":weakSelf.fsfhCtr.dataDic,@"基本信息":weakSelf.fszlCtr.dataDic,@"物料":weakSelf.fswlCtr.dataDic,@"机械":weakSelf.fsjxCtr.dataDic,@"locationInfo":weakSelf.fszlCtr.locationDic[@"locationInfo"]};
    //字典转json   RECORD_INFO
    NSString *strData=[LSUtility dictionaryToJson: dataDic];
        NSLog(@"新增:%@",strData);
    ///标题，楼层段工序
    NSDictionary* dic= weakSelf.fszlCtr.dataDic[@"工序"];
    NSString *louStr=dic[@"楼"];
    NSString *cStr=dic[@"层"];
    NSString *dStr=dic[@"段"];
    NSString *gjStr=dic[@"关键工序"];

    NSString *titleStr=[NSString stringWithFormat:@"%@楼%@层%@段%@工序",louStr,cStr,dStr,gjStr];
    
    NSString *diqu=[weakSelf.fszlCtr.dataDic objectForKey:@"地区"];
    NSString *weather=[weakSelf.fszlCtr.dataDic objectForKey:@"天气"];
    NSString *wea=[NSString stringWithFormat:@"%@/%@",diqu,weather];
    
    NSString *role=DEF_PERSISTENT_GET_OBJECT(@"role");
    if([role isEqualToString:@"USER_01"]){
        role=@"0";
    }else if ([role isEqualToString:@"USER_03"]||[role isEqualToString:@"USER_07"]){
        role=@"1";
    }
    //得到开始时间 存入创建时间
    NSString *createTime=weakSelf.fszlCtr.dataDic[@"开始时间"];
    //字段及对应值
    NSDictionary *pragameDic=[NSDictionary dictionary];
    pragameDic=@{
                 @"ID":recordId,
                 @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                 @"RECORD_USER":DEF_PERSISTENT_GET_OBJECT(@"userid"),
                 @"RECORD_MASTER":@"",
                 @"RECORD_SUPERVISION_USER":@"",
                 @"WEATHER":wea,
                 @"ADDRESS_ID":weakSelf.fszlCtr.locationDic[@"locationId"],
                 @"ADDRES_INFO":weakSelf.fszlCtr.locationDic[@"location"],
                 @"RECORD_TYPE":@"RECORD_02_02",
                 @"RECORD_TITLE":@"卷材防水施工旁站",
                 @"RECORDONTENT":@"",
                 @"RECORD_FILE_PATH":recordInFoPath,
                 @"RECORD_INFO":strData,
                 @"STATE":role,
                 @"RECORD_NUMBER":@"",
                 @"EXTEND_INFO":titleStr,
                 @"CREATE_USER_NAME":@"anonymous",
                 @"CREATE_TIME":createTime,
                 @"CREATE_IP":[LSUtility getIPAddress],
                 @"LOCAL_MODIFY_STATE":@"ADD",
                 
                 };
    BOOL isAdd=[_helper DataBase:_db insertKeyValues:pragameDic intoTable:WORK_RECORD];
    if(isAdd){
        NSLog(@"旁站-通用新增成功");
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];

        [self.navigationController popViewControllerAnimated:YES];
    }else{
        NSLog(@"旁站-通用新增失败");
    }
    
}

#pragma mark - 修改数据
- (void)upDataBase{
    WEAKSELF
    if(self.edit){
        
        NSMutableArray *fileArr= [self insertAttachment:_sideId];
        
        NSString *recordInFoPath=[LSUtility dictionaryToJson_2:fileArr];
        
        //数据结构法，存入数据库
        NSDictionary *dataDic=@{@"人":weakSelf.fsrhCtr.dataDic,@"法环":weakSelf.fsfhCtr.dataDic,@"基本信息":weakSelf.fszlCtr.dataDic,@"物料":weakSelf.fswlCtr.dataDic,@"机械":weakSelf.fsjxCtr.dataDic,@"locationInfo":weakSelf.fszlCtr.locationDic[@"locationInfo"]};
        //字典转json   RECORD_INFO
        NSString *strData=[LSUtility dictionaryToJson:dataDic];
//        NSLog(@"修改后数据:%@",strData);
        ///标题，楼层段工序
        NSDictionary* dic= weakSelf.fszlCtr.dataDic[@"工序"];
        NSString *louStr=dic[@"楼"];
        NSString *cStr=dic[@"层"];
        NSString *dStr=dic[@"段"];
        NSString *gjStr=dic[@"关键工序"];
        
        NSString *titleStr=[NSString stringWithFormat:@"%@楼%@层%@段%@工序",louStr,cStr,dStr,gjStr];
        
        NSString *diqu=[weakSelf.fszlCtr.dataDic objectForKey:@"地区"];
        NSString *weather=[weakSelf.fszlCtr.dataDic objectForKey:@"天气"];
        NSString *wea=[NSString stringWithFormat:@"%@/%@",diqu,weather];
        //字段及对应值
        NSDictionary *pragameDic=[NSDictionary dictionary];
        pragameDic=@{
                     @"RECORD_INFO":strData,
                     @"EXTEND_INFO":titleStr,
                     @"WEATHER":wea,
                     @"MODIFY_TIME":[LSUtility nowTime],
                     @"ADDRESS_ID":weakSelf.fszlCtr.locationDic[@"locationId"],
                     @"ADDRES_INFO":weakSelf.fszlCtr.locationDic[@"location"],
                     @"RECORD_FILE_PATH":recordInFoPath,
                     @"LOCAL_MODIFY_STATE":@"MOD",
                     };
        
        [_helper DataBase:_db updateTable:WORK_RECORD setKeyValues:pragameDic whereCondition:@{@"ID":self.sideId}];
        NSNotification * notice = [NSNotification notificationWithName:@"Refresh_jl_pz" object:nil userInfo:nil];
        [[NSNotificationCenter defaultCenter]postNotification:notice];
        [self.navigationController popViewControllerAnimated:YES];

    }else{
        //无法编辑，不做任何操作
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//附件存入
-(NSMutableArray *)insertAttachment:(NSString *)recordIds{
    WEAKSELF
    NSMutableArray *recordFileArr=[NSMutableArray array];;
    //人附件存入附件表
    weakSelf.fsrhCtr.selectedAssetURLs = [weakSelf.fsrhCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.fsrhCtr.selectedAssetURLs.count>0){
        NSMutableArray *rFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.fsrhCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_02" andChildType:@"RECORD_02_SIDE_01"];
        for (NSDictionary *dic in rFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //机械附件存入
    weakSelf.fsjxCtr.selectedAssetURLs = [weakSelf.fsjxCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.fsjxCtr.selectedAssetURLs.count>0){
        NSMutableArray *JXFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.fsjxCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_02" andChildType:@"RECORD_02_SIDE_02"];
        for (NSDictionary *dic in JXFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //物料附件存入
    weakSelf.fswlCtr.selectedAssetURLs = [weakSelf.fswlCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.fswlCtr.selectedAssetURLs.count>0){
        NSMutableArray *wlFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.fswlCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_02" andChildType:@"RECORD_02_SIDE_03"];
        for (NSDictionary *dic in wlFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    //法环附件存入
    weakSelf.fsfhCtr.selectedAssetURLs = [weakSelf.fsfhCtr.selectedAssetURLs valueForKeyPath:@"@distinctUnionOfObjects.self"];
    
    if(weakSelf.fsfhCtr.selectedAssetURLs.count>0){
        NSMutableArray *fhFileArr=[LSUtility insertAttachmentSiteFromArray:weakSelf.fsfhCtr.selectedAssetURLs andRecordId:recordIds andType:@"RECORD_02_02" andChildType:@"RECORD_02_SIDE_04"];
        for (NSDictionary *dic in fhFileArr) {
            [recordFileArr addObject:dic];
        }
    }
    
    return recordFileArr;
}


//!!!:创建滑动视图
- (void)createsliderBtn{
    WEAKSELF
    if(vc){
        [vc.view removeFromSuperview];
    }
    
    vc = [[SegmentViewController alloc]init];
    vc.height = DEF_SCREEN_HEIGHT - 108;
    vc.titleArray = self.titArr;
    weakSelf. fszlCtr=[[FSZLViewController alloc]init];
    weakSelf.fsrhCtr=[[FSRViewController alloc]init];
    weakSelf.fsjxCtr=[[FSJXViewController alloc]init];
    weakSelf.fswlCtr=[[FSWLViewController alloc]init];
    weakSelf.fsfhCtr=[[FSFHViewController alloc]init];
    
    NSMutableArray *controlArray = [[NSMutableArray alloc]initWithObjects:_fszlCtr,_fsrhCtr,_fsjxCtr,_fswlCtr, _fsfhCtr,nil];
    
    //查看页面
    if(![self.flag isEqualToString:@"addty"]){
        //查看详情 设置数据model
        weakSelf.fszlCtr.site=weakSelf.site;
        weakSelf.fsrhCtr.site=weakSelf.site;
        weakSelf.fsjxCtr.site=weakSelf.site;
        weakSelf.fswlCtr.site=weakSelf.site;
        weakSelf.fsfhCtr.site=weakSelf.site;
        
        weakSelf.fszlCtr.isEdit=self.edit;
        weakSelf.fsrhCtr.isEdit=self.edit;
        weakSelf.fsjxCtr.isEdit=self.edit;
        weakSelf.fswlCtr.isEdit=self.edit;
        weakSelf.fsfhCtr.isEdit=self.edit;
        
    }else{
        //添加页面 允许编辑
        weakSelf.fszlCtr.isEdit=YES;
        weakSelf.fsrhCtr.isEdit=YES;
        weakSelf.fsjxCtr.isEdit=YES;
        weakSelf.fswlCtr.isEdit=YES;
        weakSelf.fsfhCtr.isEdit=YES;
    }
    
    //设置选中字体颜色
    vc.titleSelectedColor = [TTTheme defaultManger].defaultColor;
    //设置子视图
    vc.subViewControllers = controlArray;
    //标签栏背景色
    vc.headViewBackgroundColor=[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1.00];
    //非选中状态下标签字体大小
    vc.fontSize=14.;
    //选中下划线颜色
    vc.bottomLineColor=[TTTheme defaultManger].defaultColor;
    
    vc.buttonWidth = DEF_SCREEN_WIDTH/5;
    vc.buttonHeight = 40.;
    [vc initSegment];
    [vc addParentController:self];
}
@end
